package site.overview.action;

import java.util.Iterator;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import modules.system.entity.User;
import modules.system.entity.UserRoleRel;
import modules.system.form.UserForm;
import modules.system.service.ContactService;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.guinea.core.Constants;
import com.guinea.core.acegi.AcegiCacheManager;
import com.guinea.core.service.EntityService;
import com.guinea.core.utils.StringUtils;
import com.guinea.core.web.StrutsSimpleAction;

import ex.system.service.RoleServiceEx;
import ex.system.service.UserRoleRelServiceEx;
import ex.system.service.UserServiceEx;

public class RegistActionSite extends StrutsSimpleAction {

	public static final String EDIT = "edit";

	UserServiceEx userServiceEx;

	AcegiCacheManager acegiCacheManager;

	ContactService contactService;

	UserRoleRelServiceEx userRoleRelServiceEx;

	RoleServiceEx roleServiceEx;

	public EntityService getEntityService() {
		return userServiceEx;
	}

	public UserServiceEx getUserServiceEx() {
		return userServiceEx;
	}

	public void setUserServiceEx(UserServiceEx userServiceEx) {
		this.userServiceEx = userServiceEx;
	}

	/**
	 * url参数未定义method时的默认Action函数. 默认为index Action.
	 */
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return edit(mapping, form, request, response);
	}

	/**
	 * edit验证.
	 */
	public ActionForward editValidator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		initFirst(form, request);
		return null;
	}

	/**
	 * 列出所有对象的Action函数.
	 */
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		bindForm(form, entity);

		return handleEdit(mapping, form, request, response);
	}

	protected ActionForward handleEntityMissing(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		saveError(request, "entity.missing");
		return mapping.findForward(EDIT);
	}

	protected boolean validateUserDuplicated(ActionMapping mapping,
			ActionForm form, HttpServletRequest request) {
		UserForm userForm = (UserForm) form;
		String loginName = userForm.getLoginName();
		if (!StringUtils.isEmpty(loginName)
				&& (loginName.trim().equalsIgnoreCase("admin") || getUserServiceEx()
						.getUserByLoginName(loginName) != null)) {
			saveDirectlyError(request, "该用户名已存在，不能使用。");
			return valid = false;
		}
		return true;
	}

	/**
	 * 保存对象的Action函数.
	 */
	public ActionForward ajaxValidateUser(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		validateUserDuplicated(mapping, form, request);
		renderText(response, "{\"result\":" + (valid ? 1 : 0) + "}");
		return null;
	}

	/**
	 * 保存前的验证.
	 */
	public ActionForward saveValidator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		if (isCancelled(request)) {
			valid = false;
			return mapping.findForward(EDIT);
		}

		if (!validateToken(request))
			return handleToken(mapping, form, request, response);

		initFirst(form, request);
		if (!validateUserDuplicated(mapping, form, request))
			return handleEdit(mapping, form, request, response);
		if (!validateForm(mapping, form, request))
			return handleFormErrors(mapping, form, request, response);
		return null;
	}

	/**
	 * 保存对象的Action函数.
	 */
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		doInitEntity(request, form);

		doSaveEntity(request, form);

//		RegistFormSite registFormSite = (RegistFormSite) form;
		User user = (User) entity;
//		if (!StringUtils.isEmpty(registFormSite.getEmail())) {
//			Contact contact = user.getContact();
//			if (contact == null) {
//				contact = new Contact();
//			}
//			contact.setEmail(registFormSite.getEmail());
//			contact.setUser(user);
//			getContactService().saveOrUpdate(contact);
//		}
		Set urs = user.getUserRoleRels();
		boolean hasRoleUser = false;
		for (Iterator iter = urs.iterator(); iter.hasNext();) {
			UserRoleRel userRoleRel = (UserRoleRel) iter.next();
			if (userRoleRel.getStatus().equals(Constants.STATUS_VALID)
					&& "role_user".equals(userRoleRel.getRole().getRoleName())) {
				hasRoleUser = true;
				break;
			}
		}
		if (!hasRoleUser) {
			UserRoleRel userRoleRel = new UserRoleRel();
			userRoleRel.setUser(user);
			userRoleRel.setRole(getRoleServiceEx().getRoleByRoleName(
					"role_user"));
			getUserRoleRelServiceEx().save(userRoleRel);
		}

		acegiCacheManager.refreshUserCache();

		saveMessage(request, "entity.saved");
		return new ActionForward(
				"/site/overview/contact.do?method=edit&userId="
						+ user.getId().toString(), true);
	}

	protected ActionForward handleToken(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		saveError(request, "submit.duplicated");
		return handleEdit(mapping, form, request, response);
	}

	protected ActionForward handleFormErrors(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		saveErrors(request, formErrors);
		return handleEdit(mapping, form, request, response);
	}

	protected ActionForward handleEdit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		saveToken(request);
		return mapping.findForward(EDIT);
	}

	public AcegiCacheManager getAcegiCacheManager() {
		return acegiCacheManager;
	}

	public void setAcegiCacheManager(AcegiCacheManager acegiCacheManager) {
		this.acegiCacheManager = acegiCacheManager;
	}

	public ContactService getContactService() {
		return contactService;
	}

	public void setContactService(ContactService contactService) {
		this.contactService = contactService;
	}

	public UserRoleRelServiceEx getUserRoleRelServiceEx() {
		return userRoleRelServiceEx;
	}

	public void setUserRoleRelServiceEx(
			UserRoleRelServiceEx userRoleRelServiceEx) {
		this.userRoleRelServiceEx = userRoleRelServiceEx;
	}

	public RoleServiceEx getRoleServiceEx() {
		return roleServiceEx;
	}

	public void setRoleServiceEx(RoleServiceEx roleServiceEx) {
		this.roleServiceEx = roleServiceEx;
	}

}
